//
//  MaintenanceViewController.m
//  FMS
//
//  Created by Steven on 10/15/13.
//  Copyright (c) 2013 QGSVN. All rights reserved.
//

#import "MaintenanceViewController.h"
#import "DetailedItemViewController.h"
#import "MaintenanceDetailedViewController.h"

@interface MaintenanceViewController ()

@end

@implementation MaintenanceViewController
@synthesize parent;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil itemType:(int)_itemType parent:(id)_parent
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        dictLanguage = [ApplicationDelegate.arrayLanguage objectAtIndex:0];
        itemType = _itemType;
        parent = _parent;
    }
    return self;
}

- (void) listInspectionAndMaintenance {
    NSString *itemId = [[(DetailedItemViewController*)parent detailedInfoController].itemDetailedDict objectForKey:@"_id"];
    
    [mainArray removeAllObjects];
    currentRecordIndex = 0;
    
    if (!isLock) {
//        dispatch_queue_t myQueue = dispatch_queue_create("com.myqgs.listInspectionAndMaintenance", NULL);
//        dispatch_async(myQueue, ^(void) {
            isLock = YES;
            NSMutableArray *tmpArray = [CouchBaseLiteLib listMaintenanceAndInspectionByItem:itemId from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
            
            for (int i=0;i < [tmpArray count];i++) {
                NSMutableDictionary *dict = [[tmpArray objectAtIndex:i] mutableCopy];
                
                @try {
                    //get schedule doc of this inspection
                    CBLDocument *scheduleDoc = [CouchBaseLiteLib getDocumentById:[dict objectForKey:@"scheduleId"]];
                    [dict setObject:[scheduleDoc propertyForKey:@"startDate"] forKey:@"startDate"];
                    [dict setObject:[scheduleDoc propertyForKey:@"lastUpdate"] forKey:@"lastUpdate"];
                    
                    NSString *table = [dict objectForKey:@"Table"];
                    if ([table isEqualToString:InspectionDoc])
                        [dict setObject:[dictLanguage objectForKey:@"maintenance-mgmt.service-type.inspection"] forKey:@"categoryProgram"];
                    else
                        [dict setObject:[dictLanguage objectForKey:@"maintenance-mgmt.service-type.maintenance"] forKey:@"categoryProgram"];
                    [mainArray addObject:dict];
                }
                @catch (NSException *e) {
                    NSLog(@"%@",e);
                }
            }
//            dispatch_async(dispatch_get_main_queue(), ^(void) {
//                [mainArray sortUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"startDate" ascending:NO selector:@selector(localizedCaseInsensitiveCompare:)]]];
                
                currentRecordIndex += [tmpArray count];
                
                if ([tmpArray count] == NUMBER_ROW_PAGE) {
                    isLoadMore = YES;
                }
                else {
                    isLoadMore = NO;
                }
                
                [self.mainTableView reloadData];
                
                isLock = NO;
                
                if (isLoadMore) {
//                    [self.mainTableView showLoadingMore];
                }
                else
                    [self.mainTableView hideLoadingMore];
                [self.mainTableView hideActivity];
                [myActivityView stopAnimating];
//            });
//        });
#if !OS_OBJECT_USE_OBJC
//        dispatch_release(myQueue);
#endif
//        myQueue = nil;
    }
}

- (void) listMoreInspectionAndMaintenance {
    NSString *itemId = [[(DetailedItemViewController*)parent detailedInfoController].itemDetailedDict objectForKey:@"_id"];
    
    if (!isLock) {
//        dispatch_queue_t myQueue = dispatch_queue_create("com.myqgs.listMoreInspection", NULL);
//        dispatch_async(myQueue, ^(void) {
            isLock = YES;
            NSMutableArray *tmpArray = [CouchBaseLiteLib listMaintenanceAndInspectionByItem:itemId from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
            
            for (int i=0;i < [tmpArray count];i++) {
                NSMutableDictionary *dict = [[tmpArray objectAtIndex:i] mutableCopy];
                
                //get schedule doc of this inspection
                CBLDocument *scheduleDoc = [CouchBaseLiteLib getDocumentById:[dict objectForKey:@"scheduleId"]];
                [dict setObject:[scheduleDoc propertyForKey:@"startDate"] forKey:@"startDate"];
                [dict setObject:[scheduleDoc propertyForKey:@"lastUpdate"] forKey:@"lastUpdate"];
                
                NSString *table = [dict objectForKey:@"Table"];
                if ([table isEqualToString:InspectionDoc])
                    [dict setObject:[dictLanguage objectForKey:@"maintenance-mgmt.service-type.inspection"] forKey:@"categoryProgram"];
                else
                    [dict setObject:[dictLanguage objectForKey:@"maintenance-mgmt.service-type.maintenance"] forKey:@"categoryProgram"];
                [mainArray addObject:dict];
            }
//            dispatch_async(dispatch_get_main_queue(), ^(void) {
//                [mainArray sortUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"startDate" ascending:NO selector:@selector(localizedCaseInsensitiveCompare:)]]];
                
                int previousIndex = currentRecordIndex;
                currentRecordIndex += [tmpArray count];
                
                if ([tmpArray count] == NUMBER_ROW_PAGE) {
                    isLoadMore = YES;
                }
                else {
                    isLoadMore = NO;
                }
                
                if (isLoadMore) {
                    [self.mainTableView showLoadingMore];
                }
                else
                    [self.mainTableView hideLoadingMore];
                [self.mainTableView hideActivity];
                
                NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
                for (int i=previousIndex;i < currentRecordIndex;i++) {
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                    [indexPaths addObject:indexPath];
                }
                if ([indexPaths count] > 0) {
                    [self.mainTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
                }
                
                isLock = NO;
                
//            });
//        });
#if !OS_OBJECT_USE_OBJC
//        dispatch_release(myQueue);
#endif
//        myQueue = nil;
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _lbServiceType.text     = [dictLanguage objectForKey:@"building-mgmt.maintenance.service-type"];
    _lbStartingDate.text    = [dictLanguage objectForKey:@"maintenance-mgmt.inspection.starting-date"];
    _lbEndingDate.text      = [dictLanguage objectForKey:@"maintenance-mgmt.inspection.ending-date"];
    _lbStatus.text          = [dictLanguage objectForKey:@"maintenance-mgmt.inspection.result"];
    _lbMaintenanceType.text = [dictLanguage objectForKey:@"maintenance-mgmt.maintenance.type"];
    
    _mainTableView.separatorColor = APPLE_BLUE_COLOR;
    
    mainArray = [NSMutableArray arrayWithCapacity:1];
    
    myActivityView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2, self.view.frame.size.height/2, 25, 25)];
    myActivityView.hidesWhenStopped = YES;
    myActivityView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [self.view addSubview:myActivityView];
    [myActivityView startAnimating];
    
    [self listInspectionAndMaintenance];
}

#pragma mark scrollview load more
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    didReadyLoadMore = NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    float bottomEdge = scrollView.contentOffset.y + scrollView.frame.size.height;
    if (bottomEdge >= scrollView.contentSize.height && !didReadyLoadMore)
    {
        didReadyLoadMore = YES;
        
        if(!isLoadMore)
        {
            [self.mainTableView hideLoadingMore];
            return;
        }
//        [self.mainTableView showActivity];
        [self listMoreInspectionAndMaintenance];
    }
}

#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [mainArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellIndentifier = @"CellIdentifier";
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
    
    NSMutableDictionary *dict = [mainArray objectAtIndex:indexPath.row];
    
    UILabel *lbCellServiceType = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 150, 21)];
    lbCellServiceType.backgroundColor = [UIColor clearColor];
    lbCellServiceType.textColor = [UIColor darkGrayColor];
    lbCellServiceType.text = [dict objectForKey:@"categoryProgram"];
    [cell.contentView addSubview:lbCellServiceType];
    
    UILabel *lbCellMaintenanceType = [[UILabel alloc] initWithFrame:CGRectMake(178, 20, 160, 40)];
    lbCellMaintenanceType.backgroundColor = [UIColor clearColor];
    lbCellMaintenanceType.textColor = [UIColor darkGrayColor];
    lbCellMaintenanceType.text = [ApplicationDelegate getMaintenanceName:[[dict objectForKey:@"maintenanceTypeId"] intValue]];
    [cell.contentView addSubview:lbCellMaintenanceType];
    lbCellMaintenanceType.numberOfLines = 0;
    [lbCellMaintenanceType sizeToFit];
    
    UILabel *lbCellStartDate = [[UILabel alloc] initWithFrame:CGRectMake(466, 20, 220, 21)];
    lbCellStartDate.backgroundColor = [UIColor clearColor];
    lbCellStartDate.textColor = [UIColor darkGrayColor];
    lbCellStartDate.text = [NSDate stringFormatTimeDateFromDate:[NSDate dateFormatDateFullFromString:[dict objectForKey:@"startDate"]]];
    [cell.contentView addSubview:lbCellStartDate];
    
    UILabel *lbCellEndDate = [[UILabel alloc] initWithFrame:CGRectMake(692, 20, 220, 21)];
    lbCellEndDate.backgroundColor = [UIColor clearColor];
    lbCellEndDate.textColor = [UIColor darkGrayColor];
    lbCellEndDate.text = [NSDate stringFormatTimeDateFromDate:[NSDate dateFormatDateFullFromString:[dict objectForKey:@"lastUpdate"]]];
    [cell.contentView addSubview:lbCellEndDate];
    
    UILabel *lbCellStatus = [[UILabel alloc] initWithFrame:CGRectMake(366, 20, 110, 21)];
    lbCellStatus.backgroundColor = [UIColor clearColor];
    lbCellStatus.textColor = [UIColor darkGrayColor];
    [cell.contentView addSubview:lbCellStatus];
    
    int status = [[dict objectForKey:@"workComplete"] intValue];
    if (status)
        lbCellStatus.text = [dictLanguage objectForKey:@"building-mgmt.aip.completed"];
    else
        lbCellStatus.text = [dictLanguage objectForKey:@"building-mgmt.aip.incompleted"];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableDictionary *dict = [[mainArray objectAtIndex:indexPath.row] mutableCopy];
    [(DetailedItemViewController*)parent selectDetailedMaintenance:dict];
}

@end
